package com.dmbjz.consumer;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.dmbjz.config.RabbitConfig;
import com.dmbjz.dao.OrderDetailDao;
import com.dmbjz.entity.dto.OrderMessageDTO;
import com.dmbjz.entity.po.OrderDetailPo;
import com.dmbjz.enummeration.OrderStatus;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;


/* 订单消息监听器 */
@Component
@Slf4j
public class OrderConsumer {

    @Autowired
    private OrderDetailDao orderDetailDao;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RabbitListener(queues = RabbitConfig.ORDER_QUEUE, containerFactory = "rabbitListenerContainerFactory")
    public void order(Message message, Channel channel) throws IOException {

        //1、获得JSON数据，进行反序列化
        OrderMessageDTO messageDTO = JSON.parseObject(new String(message.getBody()), OrderMessageDTO.class);        //获取订单消息
        OrderDetailPo orderDetailPo = orderDetailDao.selectOrder(messageDTO.getOrderID());                          //获取订单入库数据

        /* 创建发送消息 */
        Message deliveryMsg = null;
        MessageProperties messageProperties = new MessageProperties();
        messageProperties.setContentType(MessageProperties.CONTENT_TYPE_JSON);
        CorrelationData correlationData = new CorrelationData();

        //2、根据订单状态 进行不同的操作
        switch (messageDTO.getOrderStatus()) {

            /*餐厅已确认*/
            case RESTAURANT_CONFIRMED:

                /*判断是否创建订单且有价格，没有认为订单创建失败*/
                //没有的话，订单数据完整性没保证，这边设置订单处理失败
                if (messageDTO.getConfirmed() && null != messageDTO.getPrice()) {

                    /* 更新数据库的订单 */
                    //更新状态  更新为餐厅确认
                    orderDetailPo.setStatus(OrderStatus.RESTAURANT_CONFIRMED);
                    orderDetailPo.setPrice(messageDTO.getPrice());
                    orderDetailDao.update(orderDetailPo);

                    /* 给骑手微服务发送消息 */
                    String json = JSON.toJSONString(messageDTO);
                    deliveryMsg = new Message(json.getBytes(StandardCharsets.UTF_8), messageProperties);
                    ReturnedMessage returnedMessage = new ReturnedMessage(deliveryMsg, 200, "餐厅已确认订单,消息发送给骑手服务",
                            RabbitConfig.DELIVERYMAN_EXCHANGE, "key.deliveryman");

                    correlationData.setReturned(returnedMessage);
                    correlationData.setId(messageDTO.getOrderID());     //设置订单ID

                    rabbitTemplate.convertAndSend(RabbitConfig.DELIVERYMAN_EXCHANGE, "key.deliveryman",
                            deliveryMsg, correlationData);
                    log.info("已更新数据库订单状态,给骑手服务发送消息!");

                } else {

                    orderDetailPo.setStatus(OrderStatus.FALIED);
                    orderDetailDao.update(orderDetailPo);
                }
                break;

            /* 骑手送达确认 */
            case DELIVERTMAN_CONFIREED:

                if (StrUtil.isNotBlank(messageDTO.getDeliverymanId())) {

                    /* 更新数据库的订单 */
                    orderDetailPo.setStatus(OrderStatus.DELIVERTMAN_CONFIREED);
                    orderDetailPo.setDeliverymanId(messageDTO.getDeliverymanId());
                    orderDetailDao.update(orderDetailPo);

                    /* 给结算服务发送消息 */
                    String json = JSON.toJSONString(messageDTO);
                    deliveryMsg = new Message(json.getBytes(StandardCharsets.UTF_8), messageProperties);
                    ReturnedMessage returnedMessage = new ReturnedMessage(deliveryMsg, 200, "骑手已确认送达,消息发送给结算服务",
                            RabbitConfig.SETTLEMENT_EXCHANGE, "key.settlement");
                    correlationData.setReturned(returnedMessage);
                    correlationData.setId(messageDTO.getOrderID());     //设置订单ID
                    rabbitTemplate.convertAndSend(RabbitConfig.SETTLEMENT_EXCHANGE, "key.settlement",
                            deliveryMsg, correlationData);
                    log.info("已更新数据库订单状态,给结算服务发送消息!");

                } else {
                    orderDetailPo.setStatus(OrderStatus.FALIED);
                    orderDetailDao.update(orderDetailPo);
                }

                break;


            /* 订单结算确认 */
            case SETTLEMENT_CONFIREED:

                if (StrUtil.isNotBlank(messageDTO.getSettlementId())) {

                    /* 更新数据库的订单 */
                    orderDetailPo.setStatus(OrderStatus.SETTLEMENT_CONFIREED);
                    orderDetailPo.setSettlementId(messageDTO.getSettlementId());
                    orderDetailDao.update(orderDetailPo);

                    /* 给奖励服务发送消息 */
                    String json = JSON.toJSONString(messageDTO);
                    deliveryMsg = new Message(json.getBytes(StandardCharsets.UTF_8), messageProperties);
                    ReturnedMessage returnedMessage = new ReturnedMessage(deliveryMsg, 200, "用户订单已确认结算,消息发送给订单奖励服务",
                            RabbitConfig.REWARD_EXCHANGE, "key.reward");
                    correlationData.setReturned(returnedMessage);
                    correlationData.setId(messageDTO.getOrderID());     //设置订单ID
                    rabbitTemplate.convertAndSend(RabbitConfig.REWARD_EXCHANGE, "key.reward",
                            deliveryMsg, correlationData);
                    log.info("已更新数据库订单状态,给订单奖励服务发送消息!");

                } else {
                    orderDetailPo.setStatus(OrderStatus.FALIED);
                    orderDetailDao.update(orderDetailPo);
                }
                break;


            /* 订单结束 */
            case ORDER_CREATED:

                if (StrUtil.isNotBlank(messageDTO.getRewardId())) {

                    /* 更新数据库的订单 */
                    orderDetailPo.setStatus(OrderStatus.ORDER_CREATED);
                    orderDetailPo.setRewardId(messageDTO.getRewardId());
                    orderDetailDao.update(orderDetailPo);

                } else {
                    orderDetailPo.setStatus(OrderStatus.FALIED);
                    orderDetailDao.update(orderDetailPo);
                }
                break;

            default:
                break;

        }

        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);    //手动消息应答

    }


}
